﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Diagnostics;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;

using SAKS.Models;
using SAKS.ViewModels;
using SAKS.IServices;
using SAKS.ActionFilters;



namespace SAKS.Controllers
{
	[Authorize(Roles = "Admin,Editor")]
	public class AdminController : ControllerBase
	{
		public IMembershipServices MembershipServices { get; set; }
		public IRoleServices RoleServices { get; set; }
		public IUserServices UserServices { get; set; }


		protected override void Initialize(RequestContext requestContext)
		{
			base.Initialize(requestContext);
            var session = GetCurrentSession(requestContext);
            MembershipServices.Session = session;
			RoleServices.Session = session;
            UserServices.Session = session;
		}
        #region User & Role


        //
		// GET: /Admin/

		public ActionResult Index()
		{			
			return View();
		}


		public ActionResult AllRoles()
		{
			ViewBag.AllRoles = RoleServices.GetAllRoles();
			return View();
		}

		public ActionResult UsersInRole()
		{
			UsersInRoleModel usersInRole = new UsersInRoleModel();
			usersInRole.Role = Request["role"];
			try
			{
				IList<string> users = RoleServices.GetUsersInRole(usersInRole.Role);
				if(users.Count() == 0)
				{
					ViewData["message"] = "角色" + usersInRole.Role + "中没有用户";
					usersInRole.Users = null;
				}
				else
				{
					ViewData["message"] = null;
					usersInRole.Users = users;
				}

				return View(usersInRole);
			}
			catch (Exception e)
			{
				ViewData["message"] = e.Message;
				usersInRole.Users = null;
				return View(usersInRole);
			}
		}

		[NeedsPersistence]
		[HttpPost]
		public ActionResult RemoveFromRole()
		{
			string user = Request.Form["user"];
			string role = Request.Form["role"];
			if (user == "admin" && role == "系统管理员")
			{
				return Json(new { Message = "移除失败 - 不能将默认系统管理员从“系统管理员”角色中移除" });
			}
			if (string.IsNullOrEmpty(user) || string.IsNullOrEmpty(role))
				return Json(new { Message = "移除失败 - 参数不合法" });
			try 
			{
				RoleServices.RemoveUsersFromRoles(new string[] { user }, new string[] { role });
				return Json(new { Message = "移除成功",User = user});
			}
			catch (Exception e)
			{
				return Json(new { Message = "移除失败 - " + e.Message });        
			}
		}

		public ActionResult AddToRole()
		{
			string role = Request["role"];
			if (string.IsNullOrEmpty(role)||!RoleServices.RoleExists(role))
			{
				return RedirectToAction("AllRoles");
			}
			UserInRoleModel userInRole = new UserInRoleModel();
			userInRole.Role = role;
			return View(userInRole);
		}

		[NeedsPersistence]
		[HttpPost]
		public ActionResult AddToRole(UserInRoleModel userInRole)
		{
			string userName = userInRole.UserName;
			string role = userInRole.Role;

			if (!MembershipServices.IsUserExist(userName))
			{
				ViewData["message"] = "追加失败 - 用户不存在";
				return View(userInRole);
			}
			if(!RoleServices.RoleExists(role))
			{
				ViewData["message"] = "追加失败 - 角色不存在";
				return View(userInRole);
			}
			try
			{
				RoleServices.AddUserToRole(userInRole.UserName,userInRole.Role);
				return RedirectToAction("UsersInRole", new { role = role });
			}
			catch (Exception e)
			{
				ViewData["message"] = "追加失败 - " + e.Message;
				return View(userInRole);
			}
		}

		public ActionResult AllUsers()
		{
			int? _pageIndex = null;
			int? _pageSize = null;

			try
			{
				_pageSize = int.Parse(Request["pageSize"]);//先pageSize
				_pageIndex = int.Parse(Request["pageIndex"]);
			}
			catch (Exception)
			{
			}

			int pageIndex = _pageIndex ?? 0;
			int pageSize = _pageSize ?? 50;
			long totalRecords;

			IList<string> users = UserServices.GetAllUsers(pageIndex, pageSize, out totalRecords);
			IList<UserInRolesModel> models = new List<UserInRolesModel>();

			ViewBag.PageIndex = pageIndex;
			ViewBag.PageSize = pageSize;
			ViewBag.TotalRecords = totalRecords;
			ViewBag.Roles = RoleServices.GetAllRoles();
			ViewBag.Action = "AllUsers";

			return View(users);		
		}

		public ActionResult ChangeUserRole()
		{
			UserInRolesModel userInRole = new UserInRolesModel { 
											UserName = Request["user"],
											Roles = RoleServices.GetRolesForUser(Request["user"])??new List<string>()
											};
			ViewBag.AllRoles = RoleServices.GetAllRoles();
			return View(userInRole);
		}

		[NeedsPersistence]
		[HttpPost]
		public ActionResult ChangeUserRole(FormCollection form)
		{
			UserInRolesModel userInRoles = new UserInRolesModel();
			userInRoles.UserName = form["UserName"];
			IList<string> rolesAdd = new List<string>();
			IList<string> rolesRemove = new List<string>();
			IList<string> userRoles = RoleServices.GetRolesForUser(userInRoles.UserName);
			IList<string> allRoles = RoleServices.GetAllRoles();

			try
			{               	 
				foreach (var role in allRoles)
				{
					if (form[role] == "on")
					{
						if (!userRoles.Contains(role)) //如果role被选中且用户原来不具有此角色，则添加到待添加的角色中
						{
							rolesAdd.Add(role);
						}
					}
					else
					{
						if (userRoles.Contains(role))//如果role未被选中且用户原来具有此角色，则添加到待删除角色中
						{
							rolesRemove.Add(role);
						}
					}
				}
				if (rolesAdd.Count > 0)
					RoleServices.AddUsersToRoles(new string[] { userInRoles.UserName }, rolesAdd.ToArray());
				if (rolesRemove.Count > 0)
					RoleServices.RemoveUsersFromRoles(new string[] { userInRoles.UserName }, rolesRemove.ToArray());

				ViewData["message"] = "修改成功";

				return RedirectToAction("ModifySucceed", new { user = userInRoles.UserName });
			}
			catch (Exception e )
			{
				ViewData["message"] = "修改失败 - " + e.Message;
				return View(allRoles);
			}
		}

		public ActionResult ModifySucceed()
		{
			return View();
        }

        #endregion



    }
}
